package example.simple_mindmap.consistency.dataFunc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import example.simple_mindmap.domain.es.MindMapDOC;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Program: 8.mindmap
 * @Author: 海里的鱼
 * @Create: 2024-08-29 09:55
 * @Name: TODO
 * @Desc: TODO
 */

@Component
@RequiredArgsConstructor
public class UpdateEs implements DataFunc {

    private final RestHighLevelClient client;

    @Override
    public boolean crudData(Object data) throws Exception {
//        if(true){
////            return false;
//            throw new Exception("ES出现异常");
//        }
        MindMapDOC mindMap = BeanUtil.toBean(data, MindMapDOC.class);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("mindmap").id(mindMap.getId().toString());
        // 2.准备Json文档
        request.source(JSONUtil.toJsonStr(mindMap), XContentType.JSON);
        // 3.发送请求
        try {
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
